(function(){
	return function(){
		
		
var initDatas = function(clear,otd){
	otd = (otd==undefined)?new Date():otd;
	if(clear){
		localStorage.removeItem(DKEY);
		datas = initRangeRows(otd);
	}
	else{
		try{
			datas = JSON.parse(localStorage.getItem(DKEY));
			if(datas==null){
				initDatas(true, otd);
			}
			var ndatas = initRangeRows(otd);
			if(ndatas[0][1]!=datas[0][1]){
				initDatas(true,otd);
			}
			else if(ndatas.length!=datas.length){
				for(var i=datas.length;i<ndatas.length;i++){
					datas[i]=ndatas[i];
				}
			}
		}catch(ex){
			initDatas(true,otd);
		}
	}
}
		
var getRange = function(d, ds, de) {
	ds.setTime(d.getTime());
	de.setTime(d.getTime());
	if(d.getDate()>=21){
		ds.setDate(21);
	}
	else{
		ds.setMonth(d.getMonth()-1);
		ds.setDate(21);
	}
}

var getWeekInfo = function(day) {
	var w = ['周日','周一','周二','周三','周四','周五','周六'];
	return w[day];
}

var initRangeRows = function(d) {
	var r = [];
	var ds = new Date();
	var de = new Date();
	getRange(d, ds, de);
	var td = new Date(ds.getTime());
	if(td.getDate()!=de.getDate()){
		do {
			r.push(
				[
				new Date(td.getTime()),
				(td.getMonth()+1)+'-'+td.getDate(),
				getWeekInfo(td.getDay()),
				td.getDay()%7==0?6:td.getDay()-1,
				'待查'
				]
			);
			td.setDate(td.getDate()+1);
		} while(td.getDate()!=de.getDate());
	}
	r.push(
		[
		new Date(de.getTime()),
		(de.getMonth()+1)+'-'+de.getDate(),
		getWeekInfo(de.getDay()),
		de.getDay()%7==0?6:de.getDay()-1,
		'待查'
		]
	);
	return r;
}

var bgrangeStr = function(){
	var ds = new Date();
var now = new Date();
if(ds.getDate()>=21){ds.setDate(21);}
else {ds.setMonth(ds.getMonth()-1);ds.setDate(21);}
return ds.getFullYear()+'/'+(ds.getMonth()+1)+'/'+ds.getDate()+" 至 "+now.getFullYear()+'/'+(now.getMonth()+1)+'/'+now.getDate();
}

var ajax = function(cfg, times, try4){
	times = (undefined==times)?3:times;
	try4 = (undefined==try4)?true:try4;
	if(times<0){cfg.onfail();console.error('重试多次失败了，请重跑脚本。');return;}
	if(cfg.url){
		$.post(cfg.url,cfg.data,function(result){
			try {
				if(JSON.stringify(result).indexOf('超过8小时')!==-1 && try4){
					cfg.data['param5']='4';
					ajax(cfg, times, false);
				}
				else {
					cfg.onsuccess(result);
				}
			}catch(exe){
				cfg.onsuccess(result);
			}
		}).fail(function(xhr){
			console.error('重试'+(4-times));
			console.log(cfg);
			ajax(cfg, times-1, true);
		});
	}
	else{
		setTimeout(cfg.onsuccess,Math.ceil(Math.random()*5)*1000);
	}
}

//放弃
var  doQuery = function(onfinish) {
	try{
		console.log('报工结果查询中...');
	}catch(e){}
	var qamt = 0;
	var test = ['2017/5/15','2017/6/5'];
	datas.map(function(row){
		if(row[4]=='待查' || row[4]=='未报工'|| row[4]=='查询中'|| row[4]=='报工中'){
			qamt++;
			row[4]='查询中';
			console.log(row[1]+': '+row[4]);
		$.get('http://project.bylife.com/PowerProject/Pages/Timesheets/SubmitTimesheetSimple.aspx',function(html){
				var bgsrc = (html.match(/<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value=".*"/g));
				var bgsrc2 = (html.match(/<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value=".*"/g));
				//console.log(bgsrc[0].substring(64,bgsrc[0].length-1));console.log(bgsrc2[0].substring(82,bgsrc2[0].length-1))
		
			ajax({url:'http://project.bylife.com/PowerProject/Pages/Timesheets/SubmitTimesheetSimple.aspx',data:{
				ctl00$ScriptManager:'ctl00$Content_Body$UpdatePanel1|ctl00$Content_Body$btnPreviousWeek',
				ctl00_ScriptManager_HiddenField:'',
				ctl00$txtSearch:'',
				ctl00$hdCurrentValue:'项目',
				ctl00$Content_Body$hfFirstDayOfSelectWeek:test[qamt%2],
				ctl00$Content_Body$hfTimesheetObjectsCategory1:'',
				ctl00$Content_Body$hfTimesheetObjectsCategory2s:'',
				ctl00$Content_Body$hfTimesheetObjectsCategory3:'',
				ctl00$Content_Body$ddlOvertimeCategories:'',
				ctl00$Content_Body$ddlWorkType:'',
				ctl00$Content_Body$TimeFragmentForm$ddlStarHour:'00',
				ctl00$Content_Body$TimeFragmentForm$ddlStartMinute:'00',
				ctl00$Content_Body$TimeFragmentForm$ddlFinishHour:'00',
				ctl00$Content_Body$TimeFragmentForm$ddlFinishMinute:'00',
				ctl00$Content_Body$TimeFragmentForm$ddlWorkType:'',
				__EVENTTARGET:'ctl00$Content_Body$btnPreviousWeek',
				__EVENTARGUMENT:'',
				__VIEWSTATEGENERATOR:bgsrc2[0].substring(82,bgsrc2[0].length-1),
				__ASYNCPOST:'true',
				__VIEWSTATE:bgsrc[0].substring(64,bgsrc[0].length-1)
			},onsuccess:function(html){
				row[4]=Math.random()>0.4?'8':'未报工';
				console.log(row[1]+': '+row[4]);
				var finish = true;
				datas.map(function(ir){
					if(ir[4]=='待查' || ir[4]=='查询中'){
						finish = false;
					}
				});
				if(finish){
					console.log('查询完毕。');
					onfinish();
				}
			}}); 
		})
		}
	});
	if(qamt==0){
		console.log('查询完毕。');
		onfinish();
	}
}

var getNumFromDate= function(datestr){
	if(datestr.substr(datestr.indexOf('-')).length<3){
		return datestr.replace(/-/,'0')-0;
	}
	else{
		return datestr.replace(/-/,'')-0;
	}
}

var doBaogong = function(onfinish){
	try{
		console.log('报工中...');
	}catch(e){}
	var qamt = 0;
	var today = (new Date().getMonth()+1)+'-'+new Date().getDate();
	datas.map(function(row){
		//比较日期row[1]
		//console.log([today,getNumFromDate(today),row[1],getNumFromDate(row[1])]);
		if((getNumFromDate(today)-getNumFromDate(row[1]))<0){
			//return ;
		}
		if(row[4]=='未报工' || row[4]=='待查' ){
			//if(qamt>7) return;
			qamt++;
			row[4]='报工中';
			console.log(row[1]+': '+row[4]);
			var ds = new Date(row[0]);
			ajax({url:'http://project.bylife.com/PowerProject/Pages/Timesheets/SubmitTimesheetSimple.aspx',data:{
				isAjaxRequest:true,
				MethodName:'AddAndEditTimesheet',
				param0:'Other',
				param1:'项目任务',
				param2:bgkey,
				param3:ds.getFullYear()+'-'+(ds.getMonth()+1)+'-'+ds.getDate()+'T00:00:00+08:00',
				param4:'',
				param5:8,
				param6:'常规工作',
				param7:0,
				param8:0,
				param9:''
			},onsuccess:function(result){
				var pass = true;
				try{
				row[4]=result.ResponseData.IsSuccess?'已报工':result.ResponseData.Message;
				}catch(eee){
					pass = false;
				}
				if(pass){
					console.log(row[1]+': '+row[4]);
					
				} else {
					row[4]='未报工';
					console.log(row[1]+'报工提交异常，恢复为: '+row[4]);
					
				}
				var finish = true;
				var process = 0;
				datas.map(function(ir){
					if(ir[4]=='报工中'){
						finish = false;
					}
					else {
						process++;
					}
				});
				console.log('报工进度 ：'+process+'/'+datas.length);
				if(finish){
					console.log('报工完毕。');
					onfinish();
				}

			},onfail:function(){
				row[4]='未报工';
				console.log(row[1]+'报工提交异常，恢复为: '+row[4]);
				var finish = true;
				datas.map(function(ir){
					if(ir[4]=='报工中'){
						finish = false;
					}
				});
				if(finish){
					console.log('报工完毕。');
					onfinish();
				}
			}}); 
		}
	});
	if(qamt==0){
		console.log('报工完毕。');
		onfinish();
	}
}

var rvalid = {
cwc : 6,
cc : 0,
ct : {},
carr : [],
sv: 0,
scw:'',
go:function(){
rvalid.sv = setInterval(function(){
var cw = ctl00_Content_Body_lbWeekDay.innerText.replace(/ /gi,'');
if(rvalid.ct[cw])
{
console.log([cw,'waiting']);
}
else
{
	var dcw = new Date(cw.split('~')[1].replace(/-/g, '/')).getTime();
	if(rvalid.scw===''){
		rvalid.scw = dcw;
		ctl00_Content_Body_btnNextWeek.click();
		console.log('join next');
	}
	else if(dcw>rvalid.scw) {
		ctl00_Content_Body_btnPreviousWeek.click();
		console.log('join back');
	}
	else {
console.log([cw,'get']);
rvalid.cc++;
rvalid.ct[cw]= 'ok';
rvalid.carr.push(ctl00_Content_Body_gvTimesheet.querySelectorAll('tr')[0].outerHTML);
try{
rvalid.carr.push(ctl00_Content_Body_gvTimesheet.querySelectorAll('tr')[1].outerHTML);
}catch(ex){
}
if(rvalid.cc>=rvalid.cwc)
{
rvalid.esv();
}
else
{
ctl00_Content_Body_btnPreviousWeek.click();
}

}
}

},1000);
},
esv : function(){
$(ctl00_Content_Body_gvTimesheet).empty()
$(ctl00_Content_Body_gvTimesheet).append($(rvalid.carr.join('')));
clearInterval(rvalid.sv);	
}

}

var stopDJ = function(){
	setTimeout(function(){console.log('停止插件服务.');clearInterval(DJ);},1000);
}

		console.log('合理安排报工时间，有益于身心健康。Wish you have a good day. -- 南一luob.');
		if(-1===location.href.indexOf('SubmitTimesheetSimple.aspx')){
			if(confirm('当前页面不支持报工结果查询功能，请确认前往报工页面执行脚本')){
				location.href='http://project.bylife.com/PowerProject/Pages/Timesheets/SubmitTimesheetSimple.aspx';
			}
			return;	
		}
		var datas = [];
		var DKEY = 'BG_DATAS';
		var DJ = 0;
		
		
		var bgkey;
		
		//doQuery(function(){
			var ltd = new Date();
		console.log("本地时间："+ltd);
		console.log('获取当前用户中...');
		$.get('http://project.bylife.com/PowerProject/Pages/Users/UserInfo.aspx',function(html,status,xhr){
			
			var uid = '';//(html.match(/<span id="ctl00_Content_Body_lblLoginId">.*</g))[0].substring(41).replace(/</,'');	
			var uname = '';//(html.match(/<input name="ctl00\$Content_Body\$txtName" type="text" value=".*" id/g)[0].substring(60).replace(/" id/,''));
			try{
				uid = (html.match(/<span id="ctl00_Content_Body_lblLoginId">.*</g))[0].substring(41).replace(/</,'');	
				uname = (html.match(/<input name="ctl00\$Content_Body\$txtName" type="text" value=".*" id/g)[0].substring(60).replace(/" id/,''));
			}catch(exee){
				console.error('获取当前用户失败，无法报工');
				console.error(exee);
				return;
			}
			if(uid==''){
				console.error('获取当前用户失败，无法报工');
				return;
			}
			console.log('当前用户:'+uid+uname);
			var std = new Date(xhr.getResponseHeader('Date'));
			console.log("服务器时间："+std);

			DKEY+=uid;
			//debugger
			initDatas(false,std);
			var dev = false;
			if(dev) return;
			DJ = setInterval(function(){
				try{
					localStorage.setItem(DKEY,JSON.stringify(datas));
				}catch(exe){}
			},500);
			console.log('开启插件服务: '+DJ);
			console.log('插件自动获取报工条目，报工内容是常规工作8小时。暂不支持多条目。');
			console.log('报工周期：'+bgrangeStr());
			
			console.log('获取报工项目中...');
			var afterHqbgxm = function(bgxmid,bgxmname){
				bgkey = bgxmid;
				console.log('报工项目：'+bgxmname);
					doBaogong(function(){
						console.table([['时间','日期','星期','Day','结果']].concat(datas));
						if(new Date().getTime()>new Date('2017-7-1').getTime()){
							//for(var xx=0;xx<11;xx++)console.log(xx);
							//console.log('%c', 'padding:220px 220px; background:url("http://git.oschina.net/luob/pputil/raw/master/wxpay.png") no-repeat;')
							//console.log('谢谢支持.');
						}
						stopDJ();
						rvalid.go();
						//console.log('温馨提醒：插件使用到的$.getScript命令用于加载javascript脚本，存在泄漏登录信息的风险，使用前请确认提供脚本地址的人值得信赖。--南一部luob');
						
						console.log('------更新记录-------');
						console.log('2017年6月21日--');
						console.log('高峰期会出现报工超时问题，现增加自动重试3次的功能，如不幸重试3次都失败，则需要重跑脚本');
						console.log('报工时间段计算改为采用pp系统时间，以防本机时间不正确导致提前报工等异常操作');
						//console.log('2017年8月13日--');
						//console.log('多报工条目支持了，前提是你会使用调试工具找到报工项目的id，找到的话，试试window.zdbgxm=你找到的id;$.getScript.....');
						console.log('2018-01-02--');
						console.log('请假半天自动尝试报4小时，报工页面自动汇总显示最近一个月报工结果。');
					});
			}
			if(window.zdbgxm!==undefined){
				afterHqbgxm(window.zdbgxm,'用户指定报工项目：'+window.zdbgxm);
			}else{

			
			$.get('http://project.bylife.com/PowerProject/PC/Timesheets/AddTimesheetObjects?firstDayOfWeek=2017/6/5',function(html){
				var bgsrc = (html.substr(html.indexOf('selected=')).match(/<option value=".*">.*<\/option>/g))
				if(bgsrc.length==1){
					var ia = bgsrc[0].indexOf('"');
					var ib = bgsrc[0].indexOf('"',ia+1);
					var ic = bgsrc[0].indexOf('>');
					var id = bgsrc[0].indexOf('<',1);
					bgkey = bgsrc[0].substring(ia+1,ib);

					afterHqbgxm(bgkey,bgsrc[0].substring(ic+1,id));
					/*
					console.log('报工项目：'+bgsrc[0].substring(ic+1,id));
					doBaogong(function(){
						console.table([['时间','日期','星期','Day','结果']].concat(datas));
						if(new Date().getTime()>new Date('2017-7-1').getTime()){
							for(var xx=0;xx<11;xx++)console.log(xx);
							console.log('%c', 'padding:220px 220px; background:url("http://git.oschina.net/luob/pputil/raw/master/wxpay.png") no-repeat;')
							console.log('谢谢支持.');
						}
						stopDJ();
						console.log('温馨提醒：插件使用到的$.getScript命令用于加载javascript脚本，存在泄漏登录信息的风险，使用前请确认提供脚本地址的人值得信赖。--南一部luob');
						
						console.log('------更新记录-------');
						console.log('2017年6月21日--');
						console.log('高峰期会出现报工超时问题，现增加自动重试3次的功能，如不幸重试3次都失败，则需要重跑脚本');
						console.log('报工时间段计算改为采用pp系统时间，以防本机时间不正确导致提前报工等异常操作');
					});
					*/
				}
				else{
					console.log('获取报工项目失败，存在报工项目：'+bgsrc.length);
					console.table([['时间','日期','星期','Day','结果']].concat(datas));
					stopDJ();
				}
			
			});
			}
		});	
		//});
	}
})()();